package indi.mozping.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import indi.mozping.bean.Entity;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author by mozping
 * @Classname Util
 * @Description TODO
 * @Date 2019/2/22 14:13
 */
public class Util {

    //对应北京时间2018/01/01 00:00:00
    private static int TIME_BEGIN = 1514736000;
    //对应北京时间2019/01/01 00:00:00
    private static int TIME_BEGIN_2019 = 1546272000;
    //对应北京时间2020/01/01 00:00:00
    private static int TIME_END = 1577808000;
    //对应北京时间2019/03/31 23:59:59
    private static int TIME_END_2019_03_31 = 1554047999;
    //对应北京时间2019/02/28 23:59:59
    private static int TIME_END_2019_02_28 = 1551369599;

    private static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Entity getRandomEntity() {
        Entity entity = new Entity();
        int index = getRandomNum() % GlobalConsts.CONFIG_TOTAL_NUM_OF_PEOPLE;
        entity.setRid(getRandomNum());
        entity.setCreateName(NameBuilder.getCreateName());
        entity.setCreateTime(getTimeBetweenTwoYear());
        entity.setPeopleNum(index);
        entity.setDeviceNum(getRandomNum(GlobalConsts.CONFIG_TOTAL_NUM_OF_DEVICE));
        entity.setPeopleName(NameBuilder.nameArr.get(index));
        entity.setDeviceName("device" + entity.getDeviceNum());
        return entity;
    }

    public static int getRandomNum() {
        return getRandomNum(0, Integer.MAX_VALUE);
    }

    public static int getRandomNum(int max) {
        return getRandomNum(0, max);
    }

    //获取随机数，包括min，不包括max
    public static int getRandomNum(int min, int max) {
        return min + (int) (Math.random() * (max - min));
    }

    public static Date getTimeBetweenTwoYear() {
        int unix = getRandomNum(TIME_BEGIN, TIME_END);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }

    public static Date getTimeBetweenYear() {
        int unix = getRandomNum(TIME_BEGIN_2019, TIME_END);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }

    public static Date getTimeBetween3Month() {
        int unix = getRandomNum(TIME_BEGIN_2019, TIME_END_2019_03_31);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }

    public static Date getTimeBetween3MonthLast() {
        int unix = getRandomNum(TIME_BEGIN_2019 - 90 * 24 * 3600, TIME_BEGIN_2019 - 24 * 3600);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }

    public static Date getTimeBetween2Month() {
        int unix = getRandomNum(TIME_BEGIN_2019, TIME_END_2019_02_28);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }

    public static Date getTimeBetweenSomeDay(int days) {
        int unix = getRandomNum(TIME_BEGIN_2019, TIME_BEGIN_2019 + days * 24 * 3600);
        long unixTime = (long) unix * 1000;
        return new Date(unixTime);
    }


    public static JSONObject getSuccess() {
        JSONObject json = new JSONObject();
        json.put("response", "成功!");
        return json;
    }

    public static JSONObject getFail() {
        JSONObject json = new JSONObject();
        json.put("response", "失败!");
        return json;
    }

    public static JSONObject getFail(String msg) {
        JSONObject json = getFail();
        json.put("responseMark", msg);
        return json;
    }

    public static Date convertStringToDate(String dateStr) {
        if (dateStr == null) {
            return null;
        }

        Date date;
        SimpleDateFormat formatSecond = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            date = formatSecond.parse(dateStr);
            return date;
        } catch (ParseException pe) {

        }

        SimpleDateFormat formatMin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            date = formatMin.parse(dateStr);
            return date;
        } catch (ParseException pe) {

        }

        SimpleDateFormat formatHour = new SimpleDateFormat("yyyy-MM-dd HH");
        try {
            date = formatHour.parse(dateStr);
            return date;
        } catch (ParseException pe) {

        }

        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatDay.parse(dateStr);
            return date;
        } catch (ParseException pe) {

        }

        SimpleDateFormat formatMonth = new SimpleDateFormat("yyyy-MM");
        try {
            date = formatMonth.parse(dateStr);
            return date;
        } catch (ParseException pe) {

        }

        SimpleDateFormat formatYear = new SimpleDateFormat("yyyy");
        try {
            date = formatMonth.parse(dateStr);
            return date;
        } catch (ParseException pe) {
            return null;
        }

    }


    public static boolean isBlank(Object o) {
        if (o instanceof CharSequence) {
            CharSequence str = (CharSequence) o;
            int strLen;
            if ((strLen = str.length()) == 0) {
                return true;
            }
            for (int i = 0; i < strLen; i++) {
                if ((Character.isWhitespace(str.charAt(i)) == false)) {
                    return false;
                }
            }
            return true;
        } else {
            return (o == null) ? true : isBlank(o.toString());
        }
    }


    public static ArrayList<String> getRetKeys(String original, String split) {
        ArrayList<String> arr = new ArrayList<>();
        if (original == null || isBlank(original)) {
            return arr;
        }
        String[] str = original.split(split);
        for (String s : str) {
            if (!isBlank(s)) {
                arr.add(s.trim());
            }
        }
        return arr;
    }

    static ArrayList<String> listCarNum = new ArrayList<>();

    static {
        listCarNum.add("A");
        listCarNum.add("A");
        listCarNum.add("A");
        listCarNum.add("A");
        listCarNum.add("B");
        listCarNum.add("B");
        listCarNum.add("B");
        listCarNum.add("C");
        listCarNum.add("D");
        listCarNum.add("E");
        listCarNum.add("F");
        listCarNum.add("G");
        listCarNum.add("H");
        listCarNum.add("I");
        listCarNum.add("J");
    }

    public static String getRandomCatNum() {
        StringBuilder sb = new StringBuilder();
        sb.append("黑");
        sb.append(listCarNum.get((new Random().nextInt()) % (listCarNum.size())));
        sb.append((new Random().nextInt()) % 10);
        sb.append((new Random().nextInt()) % 10);
        sb.append((new Random().nextInt()) % 10);
        sb.append((new Random().nextInt()) % 10);
        return sb.toString();
    }


    // 车牌号的组成一般为：省份+地区代码+5位数字/字母
    public static String generateCarID() {

        char[] provinceAbbr = { // 省份简称 4+22+5+3
                '京', '津', '冀'
        };
        String alphas = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890"; // 26个字母 + 10个数字
        String alphas1 = "AAAABBBCDEFGH"; // 26个字母 + 10个数字
        Random random = new Random(); // 随机数生成器
        String carID = "";

        // 省份+地区代码+·  如 湘A· 这个点其实是个传感器，不过加上美观一些
        carID += provinceAbbr[random.nextInt(provinceAbbr.length)]; // 注意：分开加，因为加的是2个char
        carID += alphas1.charAt(random.nextInt(13));

        // 5位数字/字母
        for (int i = 0; i < 5; i++) {
            carID += alphas.charAt(random.nextInt(36));
        }
        return carID;
    }

    //对文档进行排序
//    public static JSONArray sortDoc(JSONArray jsonArray) {
//        int size = jsonArray.size();
//        Object[] arr = new Object[]{size};
//        //sort(arr,0,size-1);
//        return new JSONArray();
//    }

    public static JSONArray sortDoc(JSONArray jsonArrStr, int limit) {
        JSONArray jsonArr = jsonArrStr;
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            // You can change "time" with "ID" if you want to sort by ID
            private static final String KEY_NAME = "time";

            @Override
            public int compare(JSONObject a, JSONObject b) {
                Date da;
                Date db;
                try {
                    // 这里是a、b需要处理的业务，需要根据你的规则进行修改。
                    String aStr = a.getString(KEY_NAME);
                    da = DateUtil.convertStringToDate(aStr);
                    String bStr = b.getString(KEY_NAME);
                    db = DateUtil.convertStringToDate(bStr);
                } catch (Exception e) {
                    System.out.println("排序异常....");
                    return 1;
                }
                //时间倒序排序，如果da比db靠前，那么返回负数，da会在数组的前面，倒序之后，da较小则会放在后面
                return -da.compareTo(db);
            }
        });
        int up = limit < jsonArr.size() ? limit : jsonArr.size();
        for (int i = 0; i < up; i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }
        return sortedJsonArray;
    }

}
